import os
import sys
# 获取项目根目录
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(ROOT_DIR)

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.database.models.base import Base, User, Role, Permission, RolePermission
from app.database.models.erp import (
    # 基础信息相关
    Carrier, Airport, Airplane, HotelInfo,
    WorkArea, WorkAreaTransaction,
    
    # 客户档案相关
    CustomerProfile, CustomerPassenger, CustomerTelNo, CustomerAddress,
    
    # 机票订单相关
    AirticketOrder, AirticketOrderPassenger, AirticketOrderFlight,
    
    # 酒店订单相关
    HotelOrder, HotelOrderPassenger,
    
    # 用车订单相关
    VehicleRental,
    
    # 餐饮订单相关
    MealOrder,
    
    # 景点门票相关
    AttractionTicket,
    
    # 其他订单相关
    OtherOrder,
    
    # 打包订单相关
    PackageOrder,
    
    # 其他
    ElevyStamp
)
from app.core.config import settings

# 源数据库和目标数据库的连接配置
SOURCE_DB_URL = f"mysql+pymysql://ljy:Lijinyuan,.1983@172.28.233.235:3306/travel_agent?charset=utf8mb4"
TARGET_DB_URL = f"mysql+pymysql://ljy:Lijinyuan,.1983@120.78.7.85:3306/travel_agent?charset=utf8mb4"

# 创建数据库引擎
source_engine = create_engine(SOURCE_DB_URL)
target_engine = create_engine(TARGET_DB_URL)

# 创建会话
SourceSession = sessionmaker(bind=source_engine)
TargetSession = sessionmaker(bind=target_engine)

def migrate_table(source_session, target_session, model):
    """迁移单个表的数据"""
    print(f"开始迁移 {model.__tablename__} 表...")
    try:
        # 从源数据库读取所有记录
        records = source_session.query(model).all()
        print(f"找到 {len(records)} 条记录")

        # 写入目标数据库
        for record in records:
            # 创建新记录，排除 SQLAlchemy 特殊属性
            record_dict = {
                column.name: getattr(record, column.name)
                for column in model.__table__.columns
            }
            new_record = model(**record_dict)
            target_session.add(new_record)
        
        target_session.commit()
        print(f"{model.__tablename__} 表迁移成功！")
    except Exception as e:
        target_session.rollback()
        print(f"{model.__tablename__} 表迁移失败: {str(e)}")
        raise

def main():
    # 在目标数据库创建表结构
    Base.metadata.create_all(target_engine)
    
    # 创建会话
    source_session = SourceSession()
    target_session = TargetSession()
    
    try:
        # 按照依赖关系顺序迁移表
        models = [
            # 基础模型
            Role,
            Permission,
            RolePermission,
            WorkArea,
            User,
            
            # 基础业务信息
            Carrier,
            Airport,
            Airplane,
            HotelInfo,
            WorkAreaTransaction,
            
            # 客户相关
            CustomerProfile,
            CustomerPassenger,
            CustomerTelNo,
            CustomerAddress,
            
            # 机票订单相关
            AirticketOrder,
            AirticketOrderPassenger,
            AirticketOrderFlight,
            
            # 酒店订单相关
            HotelOrder,
            HotelOrderPassenger,
            
            # 用车订单相关
            VehicleRental,
            
            # 餐饮订单相关
            MealOrder,
            
            # 景点门票相关
            AttractionTicket,
            
            # 其他订单相关
            OtherOrder,
            
            # 打包订单相关
            PackageOrder,
            
            # 其他
            ElevyStamp
        ]
        
        # 逐个迁移表
        for model in models:
            migrate_table(source_session, target_session, model)
            
        print("所有数据迁移完成！")
        
    except Exception as e:
        print(f"迁移过程中出错: {str(e)}")
    finally:
        source_session.close()
        target_session.close()

if __name__ == "__main__":
    main() 